package edu.gxmzu.task.controller;

import com.github.pagehelper.PageInfo;
import edu.gxmzu.task.entity.UserManageInfo;
import edu.gxmzu.task.filter.JwtAuthenticationTokenFilter;
import edu.gxmzu.task.models.UserInfoModel;
import edu.gxmzu.task.service.AccountsService;
import edu.gxmzu.task.service.TaskDisposeService;
import edu.gxmzu.task.service.UserInfoService;
import edu.gxmzu.task.utils.JWTUtil;
import edu.gxmzu.task.utils.Result;
import io.lettuce.core.dynamic.annotation.Param;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

@Slf4j
@RestController
@Tag(name = "用户查询")
public class UserInfoController {

    @Autowired
    private TaskDisposeService taskDisposeService;

    @Autowired
    private UserInfoService userInfoService;

    @Resource
    private AccountsService accountService;

    @GetMapping("/getUserManageInfo")
    @Operation(summary = "用户管理页面查询", description = "用户管理页面查询，模糊查询用户名：name， 可传递，可不传递")
    public Map<String, Object> getUserManageInfo(@Param("name") String name) {

        // 创建结果集
        Map<String, Object> result = new HashMap<>();

        // 调用 Service 获取分页数据
        PageInfo<UserManageInfo> pageInfo = userInfoService.getUserManageInfo(name);

        // 返回分页数据和相关信息
        result.put("code", 200);
        result.put("data", pageInfo.getList());
        result.put("totalCount", pageInfo.getTotal());
        result.put("totalPages", pageInfo.getPages());
        result.put("status", "请求成功");

        return result;
    }


    /**
     * author: lrf
     * time: 2024-11-29
     * version : V1
     * content: 密码重置
     */
    @PostMapping("/updatePassword")
    @Operation(summary = "密码重置", description = "此处为准<br/>"+
            "{<br/>"+
            "userId:用户ID（必填）<br/>"+
            "password：新密码（必填）<br/>"+
    "}")
    public Map<String, Object> updatePassword(String userId, String password, HttpServletRequest request){
        Map<String, Object> result = new HashMap<>();
        int i = userInfoService.updatePassword(userId, password);

        if (i > 0){
            result.put("code", 200);
            result.put("status", "请求成功");
        }else{
            result.put("code", 403);
            result.put("status", "请求失败");
        }
        return result;
    }

    /**
     * author: lrf
     * time: 2024-11-29
     * version : V1
     * content: 编辑用户信息
     */
    @PostMapping("/editUserInfo")
    @Operation(summary = "编辑用户信息", description = "编辑用户信息")
    public Map<String, Object> editUserInfo(@RequestBody UserManageInfo userManageInfo){
        Map<String, Object> result = new HashMap<>();

        int i = userInfoService.editUserInfo(userManageInfo);
        if (i > 0){
            result.put("code", 200);
            result.put("status", "请求成功");
        } else {
            result.put("code", 403);
            result.put("status", "更新失败，可能是因为没有找到对应的用户或数据");
        }

        return result;
    }

    /**
     * @Author hh
     * @Description //获取个人信息数据
     * @Date 12:16 2024/12/5
     * @Param
     * @return
     **/
    @Operation(summary = "查询个人信息", description = "查询个人信息")
    @GetMapping("/UserInfo")
    public Map<String, Object> UserInfo(@RequestParam String userId,HttpServletResponse response){
        log.info("用户id"+userId);
        Map<String, Object> result = new HashMap<>();
        UserInfoModel userInfoDto = userInfoService.UserInfo(userId);
       // log.info((String) taskDisposeService.download(userInfoDto.getImg(),response));
        if(userInfoDto!=null){
            result.put("code", 200);
            result.put("status", "请求成功");
            result.put("data", userInfoDto);


        }
        else {
            result.put("code", 403);
            result.put("status", "更新失败，可能是因为没有找到对应的用户或数据");
        }

    return result;
    }

    /**
     * @Author hh
     * @Description 保存个人信息
     * @Date 14:34 2024/12/5  from-data
     * @Param@RequestBody
     * @return
     *
     *  private Long userId;  // 统一使用雪花id
     *     private String name;
     *     private String roleId;
     *     private String email;
     *     private String username;
     *     private Integer gender;  // 性别（0男，1女）
     *     private String img;  // 头像地址（每次更改直接物理删除原头像，无需建头像表，开发难度-1，用户体验-1）
     *     private String password;
     *     private String birthday;
     *
     **/
    @Operation(summary = "编辑个人信息", description = "编辑个人信息<br/>"+
            "{<br/>"+
            "必传 userId:用户id<br/>" +
            "必传name:姓名<br/>" +
            "必传roleId:角色id（0普通用户，1管理员）<br/>" +
            "email:邮箱<br/>" +
            "username:用户名<br/>" +
            "gender:性别<br/>" +
            "img:上传的头像二进制图像数据<br/>" +
            "password:密码<br/>" +
            "birthday:生日日期，传时间戳<br/>"+
            "}")
    @PostMapping("/UpdateUserInfo")
    public Result SaveUserInfo(MultipartFile file, UserInfoModel userInfoModel ) throws IOException {
        /*UserInfoModel userInfoModel = new UserInfoModel();
        String originalFilename = file.getOriginalFilename();
        Map<String, Object> result = new HashMap<>();
        if (!params.isEmpty()){
            userInfoModel.setUserId(Long.valueOf(params.get("userId")));
            userInfoModel.setName(params.get("name"));
            userInfoModel.setRoleId(params.get("roleId"));
            userInfoModel.setEmail(params.get("email"));
            userInfoModel.setUsername(params.get("username"));
            userInfoModel.setGender(Integer.valueOf(params.get("gender")));
            userInfoModel.setPassword(params.get("password"));
            userInfoModel.setBirthday(params.get("birthday"));

        }*/
        Map<String, Object> result = new HashMap<>();
        log.info("修改文件名："+file);
        if(!(file==null)) {
            String u = taskDisposeService.uploadFile1(file);
            log.info("修改文件名："+u);
            userInfoModel.setImg(u);
        }

        int userInfoDto = userInfoService.UpdateUserInfoById(userInfoModel);
        if(userInfoDto>0){
            return Result.ok("更新成功");
        }
        else {
            return Result.badRequest("缺少响应参数");
        }


    }



}
